from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import HttpResponse
from django.shortcuts import render, redirect


# Create your views here.
from myapp.models import *



@login_required
def into_home(request):
    res = {}
    res["username"] = request.user.username
    res["hrefs"] = DB_hrefs.objects.all()
    res["duans"]= DB_duan.objects.all()
    return render(request, 'home.html', res)


# 进入登录页面
def into_login(request):
    return render(request, 'login.html', {})


# 登录   表单获取前端输入框数据
def login_act(request):
    print("开始登录")
    # 获取用户名 密码
    username = request.POST.get("user", None)
    pwd = request.POST.get("pwd", None)
    # print(username, pwd)
    # 去用户表中查询这个用户名和密码 能否找到用户
    user = auth.authenticate(username=username, password=pwd)
    # print(user) 验证成功打印数据库表里的queryset的__str__, 失败则打印None
    if user:
        # 登录成功
        auth.login(request, user)
        request.session["user"] = username
        # return render(request, 'home.html', {"username": request.user.username})
        return into_home(request)  # 进入页面可能会带很多数据，里面也会用多个函数，所以改为下面这种调用方式
    else:
        # 登录失败
        # return redirect("/login/")
        return into_login(request)


# 注销
def logout(request):
    auth.logout(request)
    return redirect('/accounts/login/')


# 注册 非表单获取前端输入框数据
def register_act(request):
    # 获取数据
    username = request.POST.get("user")
    pwd = request.POST.get("pwd")
    # print(username, pwd)

    # 注册
    try:
        user = User.objects.create_user(username=username,password=pwd)
        user.save()

        # 登录
        auth.login(request, user)
        request.session["user"] = username
        # 跳转home页
        return redirect("/home/")  # 进入页面可能会带很多数据，里面也会用多个函数，所以改为下面这种调用方式
    except:
        return render(request,'login.html',{"error_msg":"注册失败！！！！！"})


def add_duan(request):
    duan = request.POST.get("name", None)
    url = request.POST.get("monitor_host", None)
    monitor_time = request.POST.get("monitor_time", None)

    print(duan,url,monitor_time)
    data = request.POST.dict()
    print(data)
    # new_duan = DB_duan.objects.create(**data)
    # new_duan.save()
    # new_duan = DB_duan.objects.create(name=duan,monitor_host=url, monitor_time = monitor_time)
    # new_duan.save()
    return redirect("/home/")

def del_duan(request,did):
    duan = DB_duan.objects.filter(id=did)
    duan.delete()
    return redirect('/home/')
    # return into_home(request)
